package weifei.wx.community.filter;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;


@WebFilter
public class CorsFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig)
            throws ServletException
    {
        Filter.super.init(filterConfig);
        System.out.println("CorsFilter init");
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException
    {
        //System.out.println("CorsFilter doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //允许请求携带认证信息(cookie)
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //指定允许其他域名访问
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        //允许请求的类型
        response.setHeader("Access-Control-Allow-Methods", "*");
        //允许的请求头字段
        response.setHeader("Access-Control-Allow-Headers", "*");
        //设置预检请求的有效期
        //浏览器同源策略：出于安全考虑，浏览器限制跨域的http请求。怎样限制呢？通过发送两次请求：预检请求、用户请求。
        //1、预检请求作用：获知服务器是否允许该跨域请求：如果允许，才发起第二次真实的请求；如果不允许，则拦截第二次请求
        //2、单位:s,在此期间不用发送预检请求。
        //3、若为0：表示每次请求都发送预检请求,每个ajax请求之前都会先发送预检请求。
        response.setHeader("Access-Control-Max-Age", "3600");
        //OPTIONS Method表示浏览器发送的预检请求。
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

